import { API_BASE_URL, handleApiResponse, type ApiResponse } from './config'

// API响应数据结构 - 周统计报表
export interface ApiWeekStatItem {
  dt: string
  requests: number
  imps: number
  clicks: number
}

// API响应数据结构 - 小时报表
export interface ApiHourReportItem {
  adspaceId: string | null
  dt: string | null
  hour: string | null
  requests: number | null
  forwards: number | null
  noAds: number | null
  lowPrices: number | null
  errors: number | null
  limits: number | null
  timeouts: number | null
  wins: number | null
  fails: number | null
  imps: number | null
  clicks: number | null
  prices: number | null
  rprices: number | null
  createTime: string | null
}

// API响应数据结构 - 日报表
export interface ApiDayReportItem {
  adspaceId: string | null
  dt: string | null
  requests: number | null
  forwards: number | null
  noAds: number | null
  lowPrices: number | null
  errors: number | null
  limits: number | null
  timeouts: number | null
  wins: number | null
  fails: number | null
  imps: number | null
  clicks: number | null
  prices: number | null
  rprices: number | null
  createTime: string | null
}

export interface ApiHourReportResponse {
  records: ApiHourReportItem[]
  totalRow: number
  pageNumber: number
  pageSize: number
}

// API响应数据结构 - 日报表
export interface ApiDayReportResponse {
  records: ApiDayReportItem[]
  totalRow: number
  pageNumber: number
  pageSize: number
}

export interface HourReportPageParams {
  current: number
  size: number
  dt?: string
  hour?: string
  adspaceId?: string
}

export interface DayReportPageParams {
  current: number
  size: number
  dt?: string
  adspaceId?: string
}

export interface SpaceDayReportParams {
  adspaceId?: string
}

export interface SpaceHourReportParams {
  adspaceId?: string
  hour?: string
}



// 获取小时报表数据
export const fetchHourReportData = async (params: HourReportPageParams): Promise<ApiHourReportResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/calcHourPage`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiHourReportResponse>(response)
  } catch (error) {
    console.error('获取小时报表数据失败:', error)
    throw error
  }
}

// 获取天的数据
export const fetchDayReportData = async (params: DayReportPageParams): Promise<ApiDayReportResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/calcDayPage`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiDayReportResponse>(response)
  } catch (error) {
    console.error('获取天报表数据失败:', error)
    throw error
  }
}

// 获取广告位天报表数据
export const fetchSpaceDayReportData = async (params: SpaceDayReportParams): Promise<ApiDayReportItem[]> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/calcSpaceDay`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiDayReportResponse>(response)
  } catch (error) {
    console.error('获取广告位天报表数据失败:', error)
    throw error
  }
}

// 获取广告位小时报表数据
export const fetchSpaceHourReportData = async (params: SpaceHourReportParams): Promise<ApiHourReportItem[]> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/calcSpaceHour`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiHourReportResponse>(response)
  } catch (error) {
    console.error('获取广告位小时报表数据失败:', error)
    throw error
  }
}

export interface HourCompareParams {
  adspaceId: string
  startDt?: string
  endDt?: string
  metric: string
}

export interface HourCompareResponse {
  adspaceId: string
  [key: string]: any // 动态的小时字段
}

// 广告位清算收入查询参数
export interface QsMediaIncomeParams {
  mediaIds?: string[] | null
  startDt?: string | null
  endDt?: string | null
}

// 获取时数据比对数据
export const fetchHourCompareData = async (params: HourCompareParams): Promise<HourCompareResponse> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/calcHourCompare`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<HourCompareResponse>(response)
  } catch (error) {
    console.error('获取时数据比对数据失败:', error)
    throw error
  }
}

// 获取周统计数据
export const fetchWeekStatData = async (): Promise<ApiWeekStatItem[]> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/weekStat`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiWeekStatItem[]>(response)
  } catch (error) {
    console.error('获取周统计数据失败:', error)
    throw error
  }
}

// API响应数据结构 - 两日数据对比
// 获取今天和昨天的两条数据，包含收入(mincomes)和成本(iprices)指标
export interface ApiTwoDayItem {
  dt: string
  mincomes: number // 收入
  iprices: number   // 成本
}

// API响应数据结构 - 广告位清算收入
export interface ApiQsMediaIncomeItem {
  mediaId: string
  mediaName: string
  adspaceId: string
  adspaceName: string
  incomeDate: string
  income: number
  request: number
  impression: number
  click: number
  realIncome: number
}

// 获取两日数据对比
// GET请求 /report/twoDay，返回今天和昨天的两条数据
export const fetchTwoDayData = async (): Promise<ApiTwoDayItem[]> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/twoDay`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiTwoDayItem[]>(response)
  } catch (error) {
    console.error('获取两日数据失败:', error)
    throw error
  }
}

// qsMediaIncome
// GET请求 /report/qsMediaIncome，返回广告位的清算收入数据
export const fetchQsMediaIncome = async (params: QsMediaIncomeParams): Promise<ApiQsMediaIncomeItem[]> => {
  try {
    const response = await fetch(`${API_BASE_URL}/report/qsMediaIncome`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return await handleApiResponse<ApiQsMediaIncomeItem[]>(response)
  } catch (error) {
    console.error('获取广告位清算收入数据失败:', error)
    throw error
  }
}